package eu.codlab.game.gameba;

import android.media.AudioFormat;
import android.media.AudioManager;
import android.media.AudioTrack;

public class AudioPlayer {
	private static AudioTrack track;

	public static boolean init(int rate, int bits, int channels){
		/*int format = bits == 16 ? AudioFormat.ENCODING_PCM_16BIT :
			AudioFormat.ENCODING_PCM_8BIT ;
		if(track != null){
			if(track.getSampleRate() == rate &&
					track.getAudioFormat() == format &&
					track.getChannelCount() == channels){
				return;
			}
			track = null;
		}*/
		int format = (bits == 16 ?
				AudioFormat.ENCODING_PCM_16BIT :
				AudioFormat.ENCODING_PCM_8BIT);
		int channelConfig = (channels == 2 ?
				AudioFormat.CHANNEL_CONFIGURATION_STEREO :
				AudioFormat.CHANNEL_CONFIGURATION_MONO);

		// avoid recreation if no parameters change
		if (track != null &&
				track.getSampleRate() == rate &&
				track.getAudioFormat() == format &&
				track.getChannelCount() == channels)
			return true;

		int bufferSize = AudioTrack.getMinBufferSize(
				rate, channelConfig, format) * 2;
		if (bufferSize < 1500)
			bufferSize = 1500;

		try {
			track = new AudioTrack(
					AudioManager.STREAM_MUSIC,
					rate,
					channelConfig,
					format,
					bufferSize,
					AudioTrack.MODE_STREAM);

			if (track.getState() == AudioTrack.STATE_UNINITIALIZED)
				track = null;

		} catch (IllegalArgumentException e) {
			track = null;
		}
		if (track == null)
			return  false;

		track.setStereoVolume(AudioTrack.getMaxVolume(), AudioTrack.getMaxVolume());
		return true;

	}

	public static void destroy(){
	}

	public static void start(){
		if (track != null)
			track.play();

	}
	public static void stop(){
		if (track != null) {
			track.stop();
			track.flush();
		}
	}
	public static void pause(){
		if (track != null) {
			track.pause();
		}	
	}
	public static void play(byte [] data, int size){
		if (track != null)
			track.write(data, 0, size);
	}

}
